import { Request, Response } from 'express';
import { scoreService } from '../../services/ai/ScoreService';
import { predictionService } from '../../services/ai/PredictionService';
import { Types } from 'mongoose';
import { z } from 'zod';
import { asyncHandler } from '../../middleware/error';
import { ApiError, ERROR_CODES } from '../../middleware/error';
import { logger } from '../../utils/logger';
import { ApiResponse } from '../../utils/apiResponse';

class AiController {
  /**
   * AI评分
   */
  evaluateAnswers = asyncHandler(async (req: Request, res: Response) => {
    logger.info('Received evaluation request', {
      userId: req.body.userId,
      subjectId: req.body.subjectId,
      answersCount: req.body.answers?.length
    });

    // 验证请求数据
    const schema = z.object({
      userId: z.string().refine(val => Types.ObjectId.isValid(val), {
        message: '无效的用户ID'
      }),
      subjectId: z.string().refine(val => Types.ObjectId.isValid(val), {
        message: '无效的科目ID'
      }),
      answers: z.array(z.object({
        questionId: z.string(),
        answer: z.string().min(1, '答案不能为空'),
        weight: z.number().optional()
      }))
    });

    const validationResult = schema.safeParse(req.body);
    if (!validationResult.success) {
      throw new ApiError(400, ERROR_CODES.INVALID_INPUT, '无效的请求数据', validationResult.error.issues);
    }

    const data = {
      ...validationResult.data,
      userId: new Types.ObjectId(validationResult.data.userId),
      subjectId: new Types.ObjectId(validationResult.data.subjectId)
    };

    const result = await scoreService.evaluateAnswers(data);

    logger.info('Evaluation completed', {
      userId: data.userId,
      subjectId: data.subjectId,
      totalScore: result.totalScore
    });

    return ApiResponse.success(res, result, '评分完成');
  });

  /**
   * 学习预测
   */
  predictLearning = asyncHandler(async (req: Request, res: Response) => {
    logger.info('Received prediction request', {
      userId: req.body.userId,
      courseId: req.body.courseId,
      assessmentsCount: req.body.assessments?.length,
      activitiesCount: req.body.activities?.length
    });

    // 验证请求数据
    const schema = z.object({
      userId: z.string().refine(val => Types.ObjectId.isValid(val), {
        message: '无效的用户ID'
      }),
      courseId: z.string().refine(val => Types.ObjectId.isValid(val), {
        message: '无效的课程ID'
      }),
      assessments: z.array(z.object({
        date: z.string().transform(val => new Date(val)),
        score: z.number().min(0).max(100),
        type: z.string()
      })),
      activities: z.array(z.object({
        date: z.string().transform(val => new Date(val)),
        duration: z.number().min(0),
        type: z.string()
      }))
    });

    const validationResult = schema.safeParse(req.body);
    if (!validationResult.success) {
      throw new ApiError(400, ERROR_CODES.INVALID_INPUT, '无效的请求数据', validationResult.error.issues);
    }

    const data = {
      ...validationResult.data,
      userId: new Types.ObjectId(validationResult.data.userId),
      courseId: new Types.ObjectId(validationResult.data.courseId)
    };

    const result = await predictionService.predictProgress(data);

    logger.info('Prediction completed', {
      userId: data.userId,
      courseId: data.courseId,
      progressRate: result.progressRate,
      riskLevel: result.riskLevel
    });

    return ApiResponse.success(res, result, '预测完成');
  });

  /**
   * 清理缓存（仅限管理员）
   */
  clearCache = asyncHandler(async (req: Request, res: Response) => {
    // 验证管理员权限
    if (req.user?.role !== 'admin') {
      throw new ApiError(403, ERROR_CODES.AUTHORIZATION_ERROR, '没有权限执行此操作');
    }

    const { type } = req.query;
    
    // 根据类型清理不同的缓存
    if (type === 'score') {
      scoreService.clearCache();
    } else if (type === 'prediction') {
      predictionService.clearCache();
    } else {
      // 清理所有缓存
      scoreService.clearCache();
      predictionService.clearCache();
    }

    logger.info('Cache cleared', { type });
    return ApiResponse.success(res, null, '缓存已清理');
  });
}

export const aiController = new AiController();
